package com.linjian.togetherbirthday.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.adapter.base.recyler.ItemWrapper;
import com.linjian.togetherbirthday.adapter.base.recyler.RecyclerAdapter;
import com.linjian.togetherbirthday.adapter.base.recyler.RecyclerHolder;
import com.linjian.togetherbirthday.base.BaseFragment;
import com.linjian.togetherbirthday.bean.HomeActivityDataBean;
import com.linjian.togetherbirthday.contant.HttpContant;
import com.linjian.togetherbirthday.util.LogUtil;
import com.linjian.togetherbirthday.utils.HttpUtils;
import com.linjian.togetherbirthday.utils.NoticeEvent;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.linjian.togetherbirthday.view.sparkbutton.SparkButton;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MyOnADateFourFragment extends BaseFragment implements XRecyclerView.LoadingListener {

    private XRecyclerView mRecyclerView;
    private RecyclerAdapter<HomeActivityDataBean.DataBean> mRecylerAdapter;
    private List<HomeActivityDataBean.DataBean> mList;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }


    @Override
    protected int setView() {
        return R.layout.fragment_my_onadate_one;
    }

    @Override
    protected void init(View view) {
        mRecyclerView = view.findViewById(R.id.me_release_on_a_date_xrv);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setArrowImageView(R.mipmap.iconfont_downgrey);

        mRecyclerView
                .getDefaultRefreshHeaderView()
                .setRefreshTimeVisible(true);
        mRecyclerView.getDefaultFootView().setLoadingHint("自定义加载中提示");
        mRecyclerView.getDefaultFootView().setNoMoreHint("自定义加载完毕提示");
        mRecyclerView.setLimitNumberToCallLoadMore(1);
        mRecyclerView.setLoadingListener(this);

        mRecylerAdapter = new RecyclerAdapter<HomeActivityDataBean.DataBean>(mItemListener) {
            @Override
            public ItemWrapper getItemHolder(int position) {
                return new ItemWrapper(R.layout.item_date_contant,HomeOneAdapter.class);
            }
        };
        mRecyclerView.setAdapter(mRecylerAdapter);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        homeActivity(1);

    }

    private OnItemListener mItemListener = new OnItemListener() {
        @Override
        public void onItemClick(View view, int position) {
            HomeActivityDataBean.DataBean dataBean = mList.get(position);
        }
    };


    HomeActivityDataBean homeActivityDataBean;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event){
        switch (event.getCls()){
            case "requestFail":
                TastyToast.makeText(getActivity(),"请求失败",TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                break;
            case "MyParticipateOnADate":
                LogUtil.e("MyParticipateOnADate",event.getData().toString());
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){
                        mList = new ArrayList<>();
                        homeActivityDataBean = new Gson().fromJson(event.getData().toString(),HomeActivityDataBean.class);
                        mList.addAll(homeActivityDataBean.getData());
                        mRecylerAdapter.addAll(mList);
                        mRecylerAdapter.notifyDataSetChanged();
                    }else {
                        TastyToast.makeText(getActivity(),object.getString("msg"),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if(mRecyclerView != null){
            mRecyclerView.destroy();
            mRecyclerView = null;
        }
    }

    /**
     * 请求首页活动
     */
    private void homeActivity(int currentPage){
        HttpUtils.doGet(HttpContant.URL + HttpContant.QueryMyActivity+"?type="+4+"&&currentPage="+currentPage
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("MyParticipateOnADate",response.body().string()));
                    }
                });
    }

    @Override
    public void onRefresh() {
        homeActivity(0);
    }

    @Override
    public void onLoadMore() {

    }


    interface OnItemListener {
        void onItemClick(View view, int position);
    }



    static class HomeOneAdapter extends RecyclerHolder<HomeActivityDataBean.DataBean> {

        private TextView releaseTimeTv,nameTv,yearTv,contantTv,addressTv,browseTv,commentsTv,cityTv,dateTimeTv,whyPayTv;
        private ImageView userIv;
        private OnItemListener mItemListener;
        private SparkButton giveLikeTv;

        public HomeOneAdapter(View itemView, OnItemListener listener) {
            super(itemView);
            userIv = itemView.findViewById(R.id.item_user_head_img);
            releaseTimeTv = itemView.findViewById(R.id.item_time);
            nameTv = itemView.findViewById(R.id.item_user_head_name);
            yearTv = itemView.findViewById(R.id.item_user_year);
            contantTv = itemView.findViewById(R.id.item_contant);
            addressTv = itemView.findViewById(R.id.item_address);
            browseTv = itemView.findViewById(R.id.item_browse_num);
            commentsTv = itemView.findViewById(R.id.item_comments_num);
            giveLikeTv = itemView.findViewById(R.id.spark_button);
            cityTv = itemView.findViewById(R.id.item_city);
            dateTimeTv = itemView.findViewById(R.id.item_date_time);
            whyPayTv = itemView.findViewById(R.id.item_why_pay);

            mItemListener = listener;
        }

        @Override
        public void onBindView(HomeActivityDataBean.DataBean dataBean) {
            releaseTimeTv.setText(String.valueOf(dataBean.getCreationtime()));
            nameTv.setText(dataBean.getNickname());
            yearTv.setText("未传");
            contantTv.setText(dataBean.getEtname());
            addressTv.setText(dataBean.getEtname());
            browseTv.setText("111人");
            commentsTv.setText("111人");
            cityTv.setText("深圳");
            dateTimeTv.setText("12-13  12：00");
            whyPayTv.setText(dataBean.getCtname());
            Glide.with(userIv.getContext()).load(dataBean.getHeadimg()).asBitmap().error(R.mipmap.user_pic).placeholder(R.mipmap.user_pic).into(userIv);
        }
    }
}
